<template>
  <div>
    <h1>Register</h1>
    <form @submit.prevent="register">
      <input v-model="name" type="name" placeholder="姓名" required />
      <input v-model="username" type="username" placeholder="登陆名" required />
      <input
        v-model="password"
        type="password"
        placeholder="Password"
        required
      />
      <button type="submit">Register</button>
    </form>
    <p v-if="error">{{ error }}</p>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { auth } from "../lib/auth-client";
import { useRouter } from "vue-router";

const name = ref("");
const username = ref("");
const password = ref("");
const error = ref<string | null>(null);
const router = useRouter();

const register = async () => {
  error.value = null;
  try {
    const result = await auth.signUp.email({
      name: name.value,
      username: username.value,
      email: `${username.value}@qq.com`,
      password: password.value,
    });

    if (result.error) {
      throw new Error(result.error.message);
    }

    alert("Registration successful! Please log in.");
    router.push("/login");
  } catch (err) {
    error.value = (err as Error).message;
  }
};
</script>
